package com.qf.service.impl;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsTopicMapper;
import com.qf.pojo.DtsDelPicture;
import com.qf.pojo.DtsTopic;
import com.qf.service.DtsStorageService;
import com.qf.service.DtsTopicService;
import com.qf.util.AliyunOSSUtil;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * author:z
 * time:2021/11/30 17:43
 * description:
 */
@Service
public class DtsTopicServiceImpl implements DtsTopicService {

    @Autowired
    DtsTopicMapper topicMapper;

    @Autowired
    DtsStorageService storageService;


    @Value("${aliyun.oss.endpoint}")
    String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    String bucketName;

    @Override
    public IPage<DtsTopic> queryPage(Integer page, Integer limit, String sort, String order, String title, String subtitle) {
        IPage<DtsTopic> iPage = new Page<>();
        QueryWrapper<DtsTopic> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(subtitle)) {
            wrapper.like("subtitle", subtitle);
        }
        if (order.equalsIgnoreCase(order)) {
            wrapper.orderByDesc(sort);
        } else {
            wrapper.orderByAsc(sort);
        }
        return iPage = topicMapper.selectPage(iPage, wrapper);
    }

    @Override
    public DtsTopic add(DtsTopic topic) {
        topic.setAddTime(new Date());
        topic.setUpdateTime(new Date());
        topic.setDeleted(false);
        topicMapper.insert(topic);
        return topic;
    }

    @Override
    public void delete(DtsTopic dtsTopic) {
        AliyunOSSUtil.deleteFile(endpoint, accessKeyId, accessKeySecret, bucketName, dtsTopic.getPicUrl());
        topicMapper.deleteById(dtsTopic.getId());
    }

    @Override
    public Object update(DtsTopic dtsTopic) {
        dtsTopic.setAddTime(new Date());
        dtsTopic.setUpdateTime(new Date());
        dtsTopic.setDeleted(false);
        if (!StringUtils.isEmpty(dtsTopic.getPicUrl())) {
            AliyunOSSUtil.deleteFile(endpoint, accessKeyId, accessKeySecret, bucketName, dtsTopic.getPicUrl());
        }
        return topicMapper.updateById(dtsTopic);
    }
}
